<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" v-show="showSearch">

      <!--请输入实验名称-->
      <el-form-item prop="name">
        <el-input v-model="queryParams.name" placeholder="Pls input Name" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <!--请选择实验状态-->
      <el-form-item prop="status">
        <el-select v-model="queryParams.status" placeholder="Select Status" clearable>
          <el-option v-for="dict in dict.type.lab_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">Search</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">Reset</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['ade:lab:add']">New</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="labList" @selection-change="handleSelectionChange">
      <el-table-column label="ID" width="45" align="center" prop="id" />
      <el-table-column label="Name" min-width="120" align="left" prop="name" show-overflow-tooltip/>
      <el-table-column label="K-fold" width="100" align="center" prop="folds" />
      <el-table-column label="Batch Size" width="100" align="center" prop="size" />
      <el-table-column label="Status" width="120" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.lab_status" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column label="Standard Status" width="150" align="center" prop="standardStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.status" :value="scope.row.standardStatus" />
        </template>
      </el-table-column>

      <el-table-column label="IncludeSource" width="180" align="left" prop="includeSource" show-overflow-tooltip>
      </el-table-column>

      <el-table-column label="ExcludeSource" width="180" align="left" prop="excludeSource" show-overflow-tooltip>
      </el-table-column>

      <el-table-column label="Description" align="left" prop="description" show-overflow-tooltip />
      <el-table-column label="Actions" width="120" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" title="Detail"
            @click="handelDetail(scope.row)"></el-button>
          <el-button v-if="scope.row.status === 'ready'" size="mini" type="text" icon="el-icon-edit" title="Edit"
            @click="handleUpdate(scope.row)" v-hasPermi="['ade:lab:edit']"></el-button>
          <el-button v-if="scope.row.status === 'ready' || scope.row.status === 'failed'" size="mini" type="text"
            icon="el-icon-position" title="Execute" @click="handleExecute(scope.row)"
            v-hasPermi="['ade:lab:edit']"></el-button>
          <el-button
            v-if="scope.row.status === 'failed' || scope.row.status === 'success' || scope.row.status === 'ready'"
            size="mini" type="text" icon="el-icon-delete" title="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['ade:lab:remove']"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改AdeLab对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" size="mini">
        <el-form-item label="Name" prop="name">
          <el-input v-model="form.name" placeholder="Pls input Name" />
        </el-form-item>
        <el-form-item label="K-fold" prop="folds">
          <el-input v-model="form.folds" placeholder="Pls input K-fold (1-20)" />
        </el-form-item>
        <el-form-item label="Batch Size" prop="size">
          <el-input v-model="form.size" placeholder="Pls input Batch Size (100~)" />
        </el-form-item>

        <el-form-item label="Standard Status" prop="standardStatus">
          <el-select v-model="form.standardStatus" placeholder="Select Standard Status" clearable>
            <el-option v-for="dict in dict.type.status" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="Include Sources" prop="includeSource">
          <el-select v-model="form.includeSource" multiple placeholder="Pls select sources" style="width: 100%;"
            clearable>
            <el-option v-for="dict in dict.type.emr_source" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="ExcludeSource" prop="excludeSource">
          <el-select v-model="form.excludeSource" placeholder="Pls select sources" multiple style="width: 100%;"
            clearable>
            <el-option v-for="dict in dict.type.emr_source" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="Description" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="Pls input description" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">Confirm</el-button>
        <el-button @click="cancel">Cancel</el-button>
      </div>
    </el-dialog>



    <!-- ADE Lab/Analysis 的详情页面 -->
    <el-dialog :visible.sync="showDialog" @close="handClose()" width="80%" :title="detailTitle">
      <ade-lab-detail-dialog v-if="selectedId" :id="selectedId" />
    </el-dialog>

  </div>
</template>

<script>
import { listLab, getLab, delLab, addLab, updateLab, executeLab } from "@/api/ade/lab";

import AdeLabDetailDialog from "@/views/ade/lab/detail.vue";

export default {
  name: "Lab",
  dicts: ['lab_status', 'status', 'emr_source'],
  components: {
    AdeLabDetailDialog,
  },
  data() {
    return {
      // AdeLab详情对话框组件相关参数
      showDialog: false,
      selectedId: null,
      detailTitle: "AdeLab Detail",

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // AdeLab表格数据
      labList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // Description时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        folds: null,
        size: null,
        status: null,
        standardStatus: null,
        includeSource: null,
        excludeSource: null,
        description: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "Name can not be empty", trigger: "blur" }

        ],
        folds: [
          { required: true, message: "K-fold can not be empty", trigger: "blur" },
          {
            pattern: /^\d+$/,  // 只允许整数（如 "123"）
            message: "K-fold must be a valid number",
            trigger: "blur"
          },
          {
            validator: (rule, value, callback) => {
              const numValue = Number(value);
              if (numValue < 1 || numValue > 20) {
                callback(new Error("K-fold must be between 1 and 20"));
              } else {
                callback(); // 验证通过
              }
            },
            trigger: "blur"
          }
        ],
        size: [
          { required: true, message: "Batch Size can not be empty", trigger: "blur" },
          {
            pattern: /^\d+$/,  // 只允许整数（如 "123"）
            message: "Batch Size must be a valid number",
            trigger: "blur"
          },
          {
            validator: (rule, value, callback) => {
              const numValue = Number(value);
              if (numValue < 100) {
                callback(new Error("Batch Size must larger than 100"));
              } else {
                callback(); // 验证通过
              }
            },
            trigger: "blur"
          }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //打开详情页面
    handelDetail(row) {
      this.detailTitle = "[ " + row.name + " ] Detail";
      this.selectedId = row.id;
      this.showDialog = true;
    },
    handClose() {
      this.showDialog = false;
      this.selectedId = null;
    },
    /** 查询AdeLab列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listLab(this.queryParams).then(response => {
        this.labList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        folds: null,
        size: null,
        status: null,
        standardStatus: null,
        includeSource: [],
        excludeSource: [],
        description: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "New AdeLab";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getLab(id).then(response => {
        this.form = response.data;

        this.form.includeSource = this.form.includeSource ? this.form.includeSource.split('#') : [];
        this.form.excludeSource = this.form.excludeSource ? this.form.excludeSource.split('#') : [];

        this.open = true;
        this.title = "Edit AdeLab";
      });
    },
    /** 执行实验 */
    handleExecute(row) {
      const id = row.id || this.ids
      this.$modal.confirm('Are you sure to execute lab："' + id + '"?').then(() => {
        executeLab(id).then(response => {
          this.$modal.msgSuccess("Execution submitted:" + response.msg);
          this.getList();
        }).catch(() => {
          // this.$modal.msgError("Execution failed");
        });
      });
    },
    /** 提交按钮 */
    submitForm() {

      // 将数组转换为字符串
      this.form.includeSource = this.form.includeSource ? this.form.includeSource.join('#') : null;
      this.form.excludeSource = this.form.excludeSource ? this.form.excludeSource.join('#') : null;
      this.form.status = 'ready'; // 默认状态为 'ready'

      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateLab(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLab(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除AdeLab编号为"' + ids + '"的数据项？').then(function () {
        return delLab(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ade/lab/export', {
        ...this.queryParams
      }, `lab_${new Date().getTime()}.xlsx`)
    },
    formatToFourDecimals(value) {
      if (!isNaN(value)) {
        const formattedValue = Number(value).toFixed(4);
        if (value > 0.9) {
          return `<span style="color: red;">${formattedValue}</span>`;
        } else if (value > 0.8) {
          return `<span style="color: orange;">${formattedValue}</span>`;
        }
        return formattedValue;
      }
      return value; // 如果不是数字，直接返回原值
    }
  }
};
</script>

<style scoped>

::v-deep .el-tabs__header {
  background-color: #fff;
  margin: 0px;
}
::v-deep .app-container {
  padding: 10px;
}

/* ::v-deep .el-dialog__header {
  padding: 10px;
}

::v-deep .el-dialog__body {
  padding: 0 !important;
} */
</style>
